<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 15/9/10
 * Time: 下午2:12
 *
 * todo 短信发送部分将来扔到消息队列中，由专用平台发送，业务不用等待回馈。
 */
class Sms
{
    const MESSAGE_SENDING = 0;
    const MESSAGE_SUCCESS = 1;
    const MESSAGE_FAIL = -1;
    /*
     * 记录短信发送状态
     * */
    public static function send_message($area,$phone,$content){
        //记录数据库
        $smsRecord = new SmsSendRecords;
        $smsRecord->area = $area;
        $smsRecord->phone = $phone;
        $smsRecord->content = $content;
        $smsRecord->status = Sms::MESSAGE_SENDING;
        $smsRecord->created_at = Common::num2DateTime(time());
        $smsRecord->save();

        $id = $smsRecord->id;
        $result = Sms::send($phone,$content,$id);
        $result = substr($result->body,74,strlen($result->body) - 74 - 9);
        $montnets_error_code = Config::get("sms.montnets_error_code");
        if($result > 0 || $result < -20000){
            $update = array('status' => 1 , 'result_msg' => '发送成功');
        }else{
            $update = array('status' => -1 , 'result_msg' => $result . ' ' . $montnets_error_code[$result]);
        }
        SmsSendRecords::updateSmsRecord($id,$update);
        return $id;
    }



    /*
     * 梦网短信发送
     * */
    public static function send($phone,$content,$id){
        $montnets = Config::get("sms.montnets");

        $request = array(
            'userId' => $montnets['userId'],
            'password' => $montnets['password'],
            'pszMobis' => $phone,
            'pszMsg' => $content,
            'iMobiCount' => $montnets['iMobiCount'],
            'pszSubPort' => $montnets['pszSubPort'],
            'MsgId' => $id
        );

        $response = Httpful::post($montnets['url'])
            ->timeoutIn(15)
            ->body($request)
            ->sendsForm()->send();
        return $response;
    }

    public static function test() {
//        $request = array(
//            'app_id' => YouyunIm::YOUYUN_IM_P_APP_ID_DEV,
//            'app_secret' => YouyunIm::YOUYUN_IM_P_APP_SECRET_DEV
//        );
//        $request = json_encode($request);
//        $response = Httpful::post($url)
//            ->addHeader('Content-Type','application/json')
//            ->timeoutIn(15)
//            ->body($request)
//            ->sendsForm()->send();
        $response = Httpful::get('http://127.0.0.1')
            ->timeoutIn(5)
            ->sendsForm()->send();
        return $response;
    }



}